package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders>
implements OrderService {

    @Autowired
    private ShoppingCartService cartService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private UserService userService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Transactional
    @Override
    public void submit(Orders orders) {
        // 在这里完成提交订单，本业务涉及多表
        // 拿到用户的Id
        Long currentId = BaseContext.getCurrentId();
        log.info("当前用户ID:{}",currentId);
        // 1. 根据用户Id ，查询购物车
        // select * from shopping_cart where user_id = 1605479590380236802;
        LambdaQueryWrapper<ShoppingCart> cartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        cartLambdaQueryWrapper.eq(ShoppingCart::getUserId, currentId);
        // 购物车列表
        List<ShoppingCart> cartList = cartService.list(cartLambdaQueryWrapper);
        if (cartList == null){
            throw new CustomException("购物车无数据，请继续去购物！！！");
        }
        // 2. 根据地址ID，查询收货地址信息
        Long addressBookId = orders.getAddressBookId();
        // select * from address_book where id = 1606952046785757185
        AddressBook addressBook = addressBookService.getById(addressBookId);
        if(addressBook == null){
            throw new CustomException("无收货地址，请添加收货地址");
        }
        // 3. 根据购物车组装订单明细，购物车列表，最终变成订单明显列表
        // 使用苞米豆提供的工具类，生成一个ID，默认是雪花算法
        Long orderId = IdWorker.getId();
        List<OrderDetail> orderDetailList = new ArrayList<>();
        // 订单的总价值
        AtomicInteger orderAmount = new AtomicInteger(0);
        int  total = 0;
        for (ShoppingCart cart:cartList){
            // 把购物车明细变订单明细，复制
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart,orderDetail);
            // 订单明细，需要设置订单的Id ,订单的ID，我们自己生成
            orderDetail.setOrderId(orderId);
            orderDetailList.add(orderDetail);
            // 计算订单的总价值
            // 计算当个的价值，数量*单价
            // 只要涉及钱的运算都是使用BigDecimal +-*/的计算方法
            // 一个商品的总价值  multiply 乘
            BigDecimal oneAmount = cart.getAmount().multiply(new BigDecimal(cart.getNumber()));
            // 累计全部的，
            orderAmount.addAndGet(oneAmount.intValue());
            // total = total+oneAmount.intValue();
        }
        // 4. 组装订单，保存订单及订单明细
        orders.setId(orderId);
        // 订单编号，公司里面有编号规则
        orders.setNumber("20221226"+orderId.toString());
        orders.setStatus(2);
        orders.setUserId(currentId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setAmount(new BigDecimal(orderAmount.intValue()));
        // 设置收货人的信息，从addressBook获取
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        // 这个就是根据addressBook吧省+市+详细地址
        orders.setAddress(addressBook.getProvinceName()+addressBook.getCityName());
        // username 下订单的人的名字，
        User user = userService.getById(currentId);
        orders.setUserName(user.getName());
        log.info("保存订单:{}",orders);
        // 保存订单
        this.save(orders);
        // 保存订单明细
        orderDetailService.saveBatch(orderDetailList);
        // 5. 清空购物车
        // delete from shopping_cart where user_id = 1605479590380236802;
        LambdaQueryWrapper<ShoppingCart> shoppingCartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        shoppingCartLambdaQueryWrapper.eq(ShoppingCart::getUserId,currentId);
        cartService.remove(shoppingCartLambdaQueryWrapper);
    }
}
